public class Solution203 {
    public ListNode removeElements(ListNode head, int val) {
        ListNode lastNode=null;
        ListNode tmpNode=head;
        ListNode newHead=head;
        while(tmpNode!=null){
            if(tmpNode.val==val){
                if(lastNode==null){
                    newHead=newHead.next;
                }
                else{
                    lastNode.next=tmpNode.next;
                }
            }
            else {
                lastNode = tmpNode;
            }
            tmpNode=tmpNode.next;
        }
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node1=new ListNode(1);
        ListNode node2=new ListNode(2);
        ListNode node3=new ListNode(2);
        ListNode node4=new ListNode(1);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        Solution203 s= new Solution203();
        s.removeElements(node1,2);
    }
}
